﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetManager.Core.Entities;
using NetManager.Core.Services;
using NetManager.Core;
using Microsoft.Practices.Composite.Presentation.Commands;
using System.Windows;
using System.IO;

namespace NetManager.LocalBrowser.ViewModels
{
    public class LocalContentViewModel : NotifyProperty, IContentModel
    {
        public LocalContentViewModel(IContentService contentService)
        {
            _contentService = contentService;
            _currentPath = contentService.CurrentPath;

            SelectedItemChange = new DelegateCommand<object>(obj =>
                {
                    CurrentPath = SelectedItem != null ? ((ContentItem)SelectedItem).FullName : string.Empty;
                    FirePropertyChanged("CurrentPath");
                });

        }

        public string CurrentPath
        {
            get { return _currentPath; }
            set
            {
                var path = value;
                if (_contentService.ValidatePath(path))
                {
                    if (_contentService.IsFile(path))
                    {
                        _contentService.Run(path);
                    }
                    else
                    {
                        _lastPath = _currentPath;
                        _currentPath = path;
                        FirePropertyChanged("Content");
                    }
                }
            }
        }
        public string Header { get { return Path.GetDirectoryName(_currentPath); } }
        public object SelectedItem { get; set; }

        public IEnumerable<ContentItem> Content
        {
            get
            {
                string message;
                IEnumerable<ContentItem> items = _contentService.GetContent(_currentPath, out message);

                if (message != null)
                {
                    MessageBox.Show(message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    items = _contentService.GetContent(_lastPath, out message);
                    _currentPath = _lastPath;
                }

                return items;
            }
        }

        public DelegateCommand<object> SelectedItemChange { get; set; }

        private string _lastPath;
        private string _currentPath;
        private IContentService _contentService;
    }
}
